package com.yan.crowd.controller;

import com.yan.crowd.api.MysqlRemoteService;
import com.yan.crowd.config.OSSProperties;
import com.yan.crowd.constant.CrowdConstant;
import com.yan.crowd.entity.vo.*;
import com.yan.crowd.util.CrownUtil;
import com.yan.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProjectController {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MysqlRemoteService mysqlRemoteService;

    /**
     * 文件上传方法..暂不做操作
     */
    @RequestMapping("/project/create/project/information")
    public String saveProjectBasicInfo(ProjectVo projectVo, MultipartFile multipartFile, List<MultipartFile> detailPictureList, HttpSession session, Model model) throws IOException {
// 一、完成头图的上传
        // 判断headerPicture对象是否为空
        boolean headerPictureEmpty = multipartFile.isEmpty();

        if (headerPictureEmpty) {
            // 头图为空，存入提示信息，且返回原本的页面
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);
            return "project-launch";
        }
        // 头图不为空 进行上传操作
        ResultEntity<String> headerPictureResultEntity = CrownUtil.uploadFileToOSS(ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                multipartFile.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                multipartFile.getOriginalFilename());
        // 判断是否上传成功
        String result = headerPictureResultEntity.getResult();
        if (ResultEntity.FAILED.equals(result)) {
            // 上传失败
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            return "project-launch";
        } else {
            // 上传成功
            // 得到存入OSS服务器的文件名
            String headerPicturePath = headerPictureResultEntity.getData();

            // 存入ProjectVO对象
            projectVo.setHeaderPicturePath(headerPicturePath);
        }

        // 二、完成详情图片的上传

        // 创建用于存放详情图片的路径的List对象
        List<String> detailPicturePathList = new ArrayList<>();

        // 判断详情图片是否为空
        if (detailPictureList == null || detailPictureList.size() == 0) {
            // 详情图片为空，加入提示信息，返回原本页面
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
            return "project-launch";
        }
        // 详情图片不为空 遍历List
        for (MultipartFile detailPicture : detailPictureList) {
            // 判断当前MultipartFile是否有效
            if (detailPicture.isEmpty()) {
                // 当前图片为空，也返回原本的页面
                model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
                return "project-launch";
            }
            // 不为空，开始存放详情图片
            ResultEntity<String> detailPictureResultEntity = CrownUtil.uploadFileToOSS(ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    detailPicture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    detailPicture.getOriginalFilename());
            // 检查上传的结果
            String detailPictureResult = detailPictureResultEntity.getResult();
            if (ResultEntity.FAILED.equals(detailPictureResult)) {
                // 上传失败
                model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                return "project-launch";
            }
            // 上传成功
            // 将当前上传后的路径放入list
            detailPicturePathList.add(detailPictureResultEntity.getData());
        }

        // 将detailPicturePathList存入ProjectVO对象
        projectVo.setDetailPicturePathList(detailPicturePathList);

        // 后续操作
        // 将ProjectVO对象放入session域
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVo);

        // 进入下一个收集回报信息的页面
        return "redirect:http://localhost/project/return/info/page.html";
    }


    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile multipartFile) throws IOException {

        ResultEntity<String> uploadPicReturnEntity = CrownUtil.uploadFileToOSS(ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                multipartFile.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                multipartFile.getOriginalFilename());

        return uploadPicReturnEntity;

    }


    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession session) {

        try {
            ProjectVo projectVo = (ProjectVo) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
            if (projectVo == null) {
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMP_PROJECT_MISSING);
            }

            // 不是自己new的对象以后操作都需要先判空
            List<ReturnVO> returnVOList = projectVo.getReturnVOList();
            if (returnVOList == null || returnVOList.size() == 0) {
                returnVOList = new ArrayList<>();
                projectVo.setReturnVOList(returnVOList);
            }

            returnVOList.add(returnVO);

            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVo);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }

    }


    @RequestMapping("/create/confirm.html")
    public String saveConfirm(HttpSession session, MemberConfirmInfoVO memberConfirmInfoVO, Model model) {

        ProjectVo projectVo = (ProjectVo) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
        if (projectVo == null) {
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMP_PROJECT_MISSING);
        }

        projectVo.setMemberConfirmInfoVO(memberConfirmInfoVO);
        MemberLoginVo memberLoginVo = (MemberLoginVo) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        Integer memberId = memberLoginVo.getId();

        ResultEntity<String> saveResult = mysqlRemoteService.saveProjectVORemote(projectVo, memberId);
        String result = saveResult.getResult();

        if (ResultEntity.FAILED.equals(result)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, saveResult.getMessage());
            return "project-confirm";
        }

        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        return "redirect://www.crowd.com/project/create/success";
    }

    @RequestMapping("/get/project/detail/{id}")
    public String getProjectDetail(@PathVariable("id") Integer id, Model model){
        ResultEntity<DetailProjectVO> detailProjectVORemote = mysqlRemoteService.getDetailProjectVORemote(id);
        String result = detailProjectVORemote.getResult();
        if (ResultEntity.SUCCESS.equals(result)){
            DetailProjectVO data = detailProjectVORemote.getData();
            model.addAttribute("detailProjectVO",data);
        }
        return "project-show-detail";
    }

}
